/*
 * @Description:
 * @Author: zhangwei
 * @Date: 2023-01-31 14:27:25
 * @LastEditTime: 2023-02-09 23:05:01
 * @LastEditors: zw 775925302@qq.com
 */

import { service } from "./service";

import { config } from "./config";
const { default_headers } = config;

function awaitWrap<T, U = any>(
  promise: Promise<T>
): Promise<[T | null, U | null]> {
  return promise
    .then<[T, null]>((data: T) => [data, null])
    .catch<[null, U]>((err) => [null, err]);
}

const serviceReq = (option: any) => {
  const { url, method, params, data, headersType, responseType } = option;
  return service({
    url: url,
    method,
    params, //get
    data, //post
    responseType: responseType,
    headers: {
      "Content-Type": headersType || default_headers,
    },
  });
};

var request = async <T = any>(option: any) => {
  const {method, params} = option;
  var _method = method.toUpperCase();
  if (_method == "GET") {
    var [res, err] = await awaitWrap(serviceReq(option));
    if (res) {
      return [res.data, err];
    }
    return [res, err];
  } else if (_method == "POST") {
    var _option = Object.assign(option);
    _option.data = params;
    _option.params = {};
    var [res, err] = await awaitWrap(serviceReq(_option));
    if (res) {
      return [res.data, err];
    }
    return [res, err];
  }

  return [null, "没有定义method:" + method + "方法处理"]
};

export { request };
// post: async <T = any>(option: any) => {
//   console.log("zzzzz")
//   const res = await request({ method: 'POST', ...option })
//     .catch(err=>{
//       console.log(err)
//     })
//   console.log("xxxxttt",res)
//   return res.data as unknown as T
// },
// postOriginal: async (option: any) => {
//   const res = await request({ method: 'POST', ...option })
//   return res
// },
// delete: async <T = any>(option: any) => {
//   const res = await request({ method: 'DELETE', ...option })
//   return res.data as unknown as T
// },
// put: async <T = any>(option: any) => {
//   const res = await request({ method: 'PUT', ...option })
//   return res.data as unknown as T
// },
// download: async <T = any>(option: any) => {
//   const res = await request({ method: 'GET', responseType: 'blob', ...option })
//   return res as unknown as Promise<T>
// },
// upload: async <T = any>(option: any) => {
//   option.headersType = 'multipart/form-data'
//   const res = await request({ method: 'POST', ...option })
//   return res as unknown as Promise<T>
// }
// };
